package com.ad.aidai.fragments.bind_school;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.bean.School;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.widgets.edittext.ClearEditText;
import com.ad.aidai.common.widgets.edittext.PasswordEditText;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.select_school.SelectSchoolFragment;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by pure on 2017/1/18.
 */

public class BindSchoolFragment extends BaseFragment implements BindSchoolContract.View {

    @BindView(R.id.tv_school_select)
    TextView tvSchoolSelect;
    @BindView(R.id.et_stu_num)
    ClearEditText etStuNum;
    @BindView(R.id.et_pass)
    PasswordEditText etPass;

    private BindSchoolContract.Presenter mPresenter;

    private LoadingDialog loadingDialog;

    private int schoolId = 0;
    private String schoolName;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_bind_school, container, false);
        mView.setClickable(true);//防止点击穿透，底层的fragment响应上层点击触摸事件
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        new BindSchoolPresenter(mContext, this).subscribe();

    }

    @Override
    public void setPresenter(BindSchoolContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick({R.id.iv_back, R.id.rl_school, R.id.bt_bind})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (etStuNum.isFocused()) {
                    closeSoftInput(etStuNum);
                } else if (etPass.isFocused()) {
                    closeSoftInput(etPass);
                }
                onActivityBackPressed();
                break;
            case R.id.rl_school:
                getFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                .fragment_slide_left_exit)
                        .add(android.R.id.content, new SelectSchoolFragment(), "profile")
                        .addToBackStack("profile")
                        .commit();
                if (etStuNum.isFocused()) {
                    closeSoftInput(etStuNum);
                } else if (etPass.isFocused()) {
                    closeSoftInput(etPass);
                }
                break;
            case R.id.bt_bind:
//                String school = tvSchoolSelect.getText().toString();
                String stuNum = etStuNum.getText().toString();
                String pass = etPass.getText().toString();
                mPresenter.bindSchool(schoolId, schoolName, stuNum, pass);
                break;

        }
    }

    @Override
    public void showSelectedSchool(String schoolName) {
        tvSchoolSelect.setText(schoolName);
        tvSchoolSelect.setTextColor(Color.BLACK);
    }

    @Override
    protected void subscribeEvents() {
        //订阅事件
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (o instanceof CommonEvent) {
                            CommonEvent event = (CommonEvent) o;
                            switch (event.getEvent()) {
                                case CommonEvent.SELECT_SCHOOL_BIND:
                                    mPresenter.selectSchool((School) event.getData());
                                    schoolId = ((School) event.getData()).getSchoolId();
                                    schoolName = ((School) event.getData()).getSchoolName();
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber()));
    }

    /**
     * 关闭软键盘
     *
     * @param view 对应的EditText
     */
    public void closeSoftInput(View view) {
        InputMethodManager inputManager = (InputMethodManager) mActivity.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    public void bindSuccess() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog.isShowing()) {

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (etStuNum.isFocused()) {
                            closeSoftInput(etStuNum);
                        } else if (etPass.isFocused()) {
                            closeSoftInput(etPass);
                        }
                        getFragmentManager().popBackStack();
                    }
                });
            }
        }).start();

//        getFragmentManager().popBackStack();
//        RxBus.getInstance().postEvent(new CommonEvent(CommonEvent.SCHOOL_INFO_BIND));
//        if (etStuNum.isFocused()) {
//            closeSoftInput(etStuNum);
//        } else if (etPass.isFocused()) {
//            closeSoftInput(etPass);
//        }
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mActivity);
        loadingDialog.setLoadingText("绑定中...")
                .setFailedText("绑定失败")
                .setSuccessText("绑定成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public boolean onActivityBackPressed() {
        getFragmentManager().popBackStack();
        return false;
    }
}